<template>
  <div class="special-operation-ranking">
    <!-- 页面标题 -->
    <div class="ranking-header">
      <n-space align="center" :size="12">
        <n-icon :size="24" color="#e6a23c">
          <BusinessOutline />
        </n-icon>
        <div>
          <n-text strong style="font-size: 20px;">特勤处排行榜</n-text>
          <n-text :depth="3" style="font-size: 14px; margin-left: 8px;">
            查看特勤处操作的利润、效率和热门度排行
          </n-text>
        </div>
      </n-space>
    </div>

    <!-- 筛选器 -->
    <ranking-filters
      v-model:filters="filters"
      :loading="loading"
      :location-stats="locationStats"
      @filter-change="handleFilterChange"
      @update:filters="handleFiltersUpdate"
    />

    <!-- 排行榜内容 -->
    <div class="ranking-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <n-spin size="large">
          <template #description>
            <n-text :depth="3">正在加载特勤处数据...</n-text>
          </template>
        </n-spin>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <n-result status="error" title="加载失败" :description="error">
          <template #footer>
            <n-button @click="loadData" type="primary">
              重新加载
            </n-button>
          </template>
        </n-result>
      </div>

      <!-- 空数据状态 -->
      <div v-else-if="!items.length" class="empty-container">
        <n-empty description="暂无特勤处数据">
          <template #icon>
            <n-icon :size="48" :depth="3">
              <BusinessOutline />
            </n-icon>
          </template>
          <template #extra>
            <n-button @click="loadData" size="small">
              刷新数据
            </n-button>
          </template>
        </n-empty>
      </div>

      <!-- 排行榜列表 -->
      <ranking-list
        v-else
        :items="items"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        :loading="loading"
        :material-infos="materialInfos"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        @item-click="handleItemClick"
        @sort-change="handleSortChange"
      />
    </div>

    <!-- 统计信息 -->
    <div v-if="stats && !loading" class="stats-section">
      <n-card title="数据统计" size="small">
        <n-grid :cols="2" :x-gap="16" :y-gap="12" responsive="screen">
          <n-grid-item>
            <n-statistic label="总操作数" :value="stats.totalItems" />
          </n-grid-item>
          <n-grid-item>
            <n-statistic 
              label="平均利润" 
              :value="stats.avgProfit" 
              :precision="2"
              suffix="哈夫币"
            />
          </n-grid-item>
          <n-grid-item>
            <n-statistic 
              label="平均周期" 
              :value="stats.avgCycle" 
              :precision="1"
              suffix="小时"
            />
          </n-grid-item>
          <n-grid-item>
            <n-statistic label="热门位置" :value="stats.topLocation" />
          </n-grid-item>
        </n-grid>
      </n-card>
    </div>

    <!-- 物品详情弹窗 -->
    <ItemDetailModal
      v-model:show="showDetailModal"
      :object-id="selectedItemId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { BusinessOutline } from '@vicons/ionicons5'
import { useMessage } from 'naive-ui'
import { getSpecialOperationList, getBulkMaterialInfo } from '@/api/specialOperation'
import type {
  SpecialOperationItem,
  SpecialOperationQueryParams,
  FilterState,
  SpecialOperationStats,
  MaterialInfo
} from '@/types/specialOperation'

// 导入子组件
import RankingFilters from '../components/SpecialOperation/RankingFilters.vue'
import RankingList from '../components/SpecialOperation/RankingList.vue'
import ItemDetailModal from '@/components/ItemDetailModal.vue'

// 引入特勤处排行榜样式
import '@/styles/components/ranking/SpecialOperationRanking.css'

// 响应式数据
const loading = ref(false)
const error = ref('')
const items = ref<SpecialOperationItem[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 详情弹窗相关状态
const showDetailModal = ref(false)
const selectedItemId = ref<number | null>(null)

// 位置统计数据
const locationStats = ref<Record<string, number>>({})

// 材料信息缓存
const materialInfos = ref<Record<string, MaterialInfo>>({})

// 筛选器状态
const filters = reactive<FilterState>({
  location: '',
  minProfit: null,
  maxCycle: null,
  sortBy: 'lirun',
  sortOrder: 'desc'
})

// 消息提示
const message = useMessage()

// 解析材料字符串
const parseCustomMaterials = (rawMaterials: string): Record<string, number> => {
  if (!rawMaterials || typeof rawMaterials !== 'string') {
    return {}
  }

  const materials: Record<string, number> = {}
  try {
    const pairs = rawMaterials.split(',')
    for (const pair of pairs) {
      const trimmedPair = pair.trim()
      if (!trimmedPair) continue

      const parts = trimmedPair.split(':')
      if (parts.length === 2) {
        const id = parts[0].trim()
        const countStr = parts[1].trim()
        const count = parseInt(countStr, 10)

        if (id && !isNaN(count) && count > 0) {
          materials[id] = count
        }
      }
    }
  } catch (error) {
    console.warn('解析材料字符串失败:', error)
    return {}
  }

  return materials
}

// 计算统计数据
const stats = computed<SpecialOperationStats | null>(() => {
  if (!items.value.length) return null
  
  const totalItems = items.value.length
  const avgProfit = items.value.reduce((sum, item) => sum + item.lirun, 0) / totalItems
  const avgCycle = items.value.reduce((sum, item) => sum + item.period, 0) / totalItems
  
  // 统计最热门位置
  const locationCount: Record<string, number> = {}
  items.value.forEach(item => {
    locationCount[item.location] = (locationCount[item.location] || 0) + 1
  })
  const topLocation = Object.keys(locationCount).reduce((a, b) => 
    locationCount[a] > locationCount[b] ? a : b
  )
  
  // 最高利润和最快速度的物品
  const mostProfitableItem = items.value.reduce((max, item) => 
    item.lirun > max.lirun ? item : max
  )
  const fastestItem = items.value.reduce((min, item) => 
    item.period < min.period ? item : min
  )
  
  return {
    totalItems,
    avgProfit,
    avgCycle,
    topLocation,
    mostProfitableItem,
    fastestItem
  }
})

// 批量加载材料信息
const loadMaterialInfos = async (items: SpecialOperationItem[]) => {
  try {
    // 收集所有材料ID
    const allMaterialIds = new Set<string>()

    // 从所有项目中提取材料ID
    for (const item of items) {
      const materialsObject = parseCustomMaterials(item.materials)
      Object.keys(materialsObject).forEach(id => allMaterialIds.add(id))
    }

    // 筛选出未缓存的材料ID
    const missingIds = Array.from(allMaterialIds).filter(id => !materialInfos.value[id])

    // 如果有未缓存的材料，批量加载
    if (missingIds.length > 0) {
      console.log('批量加载材料信息，IDs:', missingIds)
      const response = await getBulkMaterialInfo(missingIds)

      if (response.code === 1 && response.data) {
        // 更新材料信息缓存
        for (const id in response.data) {
          if (Object.prototype.hasOwnProperty.call(response.data, id)) {
            materialInfos.value[id] = response.data[id]
          }
        }
        console.log('材料信息加载完成，缓存数量:', Object.keys(materialInfos.value).length)
      } else {
        console.warn('批量获取材料信息失败:', response.msg)
      }
    }
  } catch (error: any) {
    console.error('加载材料信息时发生错误:', error)
    message.error('加载材料信息失败')
  }
}

// 加载位置统计数据
const loadLocationStats = async () => {
  try {
    // 获取所有数据来统计位置数量（不分页）
    const statsParams: SpecialOperationQueryParams = {
      page: 1,
      page_size: 10000, // 获取大量数据来统计
      min_profit: filters.minProfit || undefined,
      max_cycle: filters.maxCycle || undefined
    }

    const response = await getSpecialOperationList(statsParams)

    if (response.code === 1 && response.data) {
      const allItems = response.data.list || []
      const stats: Record<string, number> = {}

      // 统计各个位置的数量
      allItems.forEach(item => {
        const location = item.location || '未知'
        stats[location] = (stats[location] || 0) + 1
      })

      locationStats.value = stats
    }
  } catch (err: any) {
    console.error('加载位置统计失败:', err)
  }
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    error.value = ''

    const params: SpecialOperationQueryParams = {
      page: currentPage.value,
      page_size: pageSize.value,
      location: filters.location && filters.location.trim() !== '' ? filters.location : undefined,
      min_profit: filters.minProfit || undefined,
      max_cycle: filters.maxCycle || undefined,
      sort_by: filters.sortBy,
      sort_order: filters.sortOrder
    }

    const response = await getSpecialOperationList(params)

    if (response.code === 1 && response.data) {
      items.value = response.data.list || []
      total.value = response.data.total || 0
      currentPage.value = response.data.page || 1
      pageSize.value = response.data.page_size || 20

      // 加载材料信息
      if (items.value.length > 0) {
        await loadMaterialInfos(items.value)
      }
    } else {
      throw new Error(response.msg || '获取数据失败')
    }
  } catch (err: any) {
    error.value = err.message || '加载特勤处数据失败'
    message.error(error.value)
  } finally {
    loading.value = false
  }
}

// 处理筛选器更新
const handleFiltersUpdate = (newFilters: FilterState) => {
  Object.assign(filters, newFilters)
}

// 处理筛选器变化
const handleFilterChange = () => {
  currentPage.value = 1 // 重置到第一页
  loadData()
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadData()
}

// 处理页面大小变化
const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
  loadData()
}

// 处理排序变化
const handleSortChange = (sortInfo: { key: string, order: 'ascend' | 'descend' | false }) => {
  console.log('排序变化:', sortInfo)

  // 映射表格列key到API排序字段
  const sortFieldMap: Record<string, string> = {
    'sale_price': 'sale_price',
    'cost_price': 'cost_price',
    'fee': 'fee',
    'bail': 'bail',
    'lirun': 'lirun',
    'period': 'period',
    'per_count': 'per_count',
    'profit_per_hour': 'profit_per_hour'
  }

  if (sortInfo.key && sortInfo.order) {
    const apiField = sortFieldMap[sortInfo.key]
    if (apiField) {
      filters.sortBy = apiField as any
      filters.sortOrder = sortInfo.order === 'ascend' ? 'asc' : 'desc'
      currentPage.value = 1 // 重置到第一页
      loadData()
    }
  }
}

// 显示物品详情
const showItemDetail = (objectId: number) => {
  console.log('SpecialOperationRanking: 点击显示物品详情, objectId:', objectId)
  selectedItemId.value = objectId
  showDetailModal.value = true
  console.log('SpecialOperationRanking: 设置状态完成, selectedItemId:', selectedItemId.value, 'showDetailModal:', showDetailModal.value)
}

// 处理物品点击事件
const handleItemClick = (item: SpecialOperationItem & { rank: number }) => {
  showItemDetail(item.object_id)
}

// 监听筛选器变化
watch(filters, () => {
  handleFilterChange()
}, { deep: true })

// 组件挂载时加载数据
onMounted(() => {
  loadData()
  loadLocationStats()
})
</script>

<style scoped>
.special-operation-ranking {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 0;
}

.ranking-header {
  padding: 16px 10px;
  border-bottom: 1px solid var(--n-border-color);
}

.ranking-content {
  min-height: 400px;
}

.loading-container,
.error-container,
.empty-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.stats-section {
  margin-top: 20px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .special-operation-ranking {
    gap: 16px;
  }
  
  .ranking-header {
    padding: 12px 0;
  }
  
  .ranking-content {
    min-height: 300px;
  }
}
</style>
